import editForm from "../form.vue";
import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
import { removeEmptyValues } from "@/utils/common";

import { type Ref, reactive, ref, onMounted, h, toRaw, watch } from "vue";
import {  getLogListForPub } from "@/api/logs";
import { logInfoType } from "@/utils/commonType";
import { FieldValues, PlusColumn } from "plus-pro-components";
import { getAccount } from "@/utils/auth";

export function useAccount(treeRef: Ref) {
  const form = reactive({
    appName: null,
    serviceName: null,
    callDate: [],
    startCallDate: null,
    endCallDate: null
  });
  const curRow = ref();
  const dataList = ref([]);
  const treeIds = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const detailVisible = ref(false);
  const detailInfo = ref<FieldValues>();

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const columnsForTable: TableColumnList = [
    {
      label: "序号",
      type: "index",
      width: 60
    },
    {
      label: "应用名称",
      prop: "appName"
    },
    {
      label: "服务名称",
      prop: "serviceName"
    },
    {
      label: "服务地址",
      prop: "callServiceRealUrl",
      minWidth: 160
    },
    {
      label: "调用时间",
      prop: "reqDate",
      minWidth: 160
    },
    {
      label: "响应状态",
      prop: "resStatus",
      minWidth: 90
    },
    {
      label: "处理状态",
      prop: "optStatus",
      minWidth: 90
    },
    {
      label: "处理结果",
      prop: "optReson",
      minWidth: 90
    },
    {
      label: "操作",
      fixed: "right",
      width: 80,
      slot: "operation"
    }
  ];

  const columns: PlusColumn[] = [
    {
      label: "服务名称",
      width: 160,
      prop: "serviceName",
      valueType: "text"
    },
    {
      label: "服务URL",
      width: 160,
      prop: "callServiceRealUrl",
      valueType: "text"
    },
    {
      label: "发布租户",
      width: 160,
      prop: "pubTenantName",
      valueType: "text"
    },
    {
      label: "发布应用",
      width: 160,
      prop: "appName",
      valueType: "text"
    },
    {
      label: "调用租户",
      width: 160,
      prop: "tenantName",
      valueType: "text"
    },
    {
      label: "调用端",
      width: 160,
      prop: "callClientName",
      valueType: "text"
    },
    {
      label: "调用端IP",
      width: 160,
      prop: "clientIp",
      valueType: "text"
    },
    {
      label: "调用信息",
      width: 160,
      prop: "requestUrl",
      valueType: "text"
    },
    {
      label: "调用时间",
      width: 160,
      prop: "reqDate",
      valueType: "text"
    },
    {
      label: "耗时-毫秒",
      width: 160,
      prop: "resTime",
      valueType: "text"
    },
    {
      label: "响应状态",
      width: 160,
      prop: "resStatus",
      valueType: "text"
    },
    {
      label: "处理状态",
      width: 160,
      prop: "optStatus",
      valueType: "text"
    },
    {
      label: "处理结果",
      width: 160,
      prop: "optReson",
      valueType: "text"
    },
    {
      label: "请求头",
      width: 160,
      prop: "reqHeaders",
      valueType: "text"
    },
    {
      label: "请求参数",
      width: 160,
      prop: "reqParams",
      valueType: "text"
    },
    {
      label: "请求体",
      width: 160,
      prop: "reqBody",
      valueType: "text"
    },
    {
      label: "响应体",
      width: 160,
      prop: "resBody",
      valueType: "text"
    }
  ];

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onRefash();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function openLogDetail(row?: logInfoType) {
    detailVisible.value = true;
    detailInfo.value = row;
  }

  function mergedParams() {
    const data = {
      ...toRaw(form),
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    };

    return removeEmptyValues(data);
  }

  async function onSearch() {
    loading.value = true;
    pagination.currentPage = 1;

    form.startCallDate = form.callDate == null ? null : form.callDate[0];
    form.endCallDate = form.callDate == null ? null : form.callDate[1];
    const curTenantId = getAccount().tenantId;
    getLogListForPub(curTenantId, mergedParams())
      .then(function (data) {
        dataList.value = data.data.list;
        pagination.total = data.data.total;
        pagination.pageSize = data.data.pageSize;
        pagination.currentPage = data.data.currentPage;
        pagination.pageCount = data.data.totalPage;
      })
      .catch(function (err) {
        message(`账户清单加载异常：${err.message}`, {
          type: "error"
        });
      });
    loading.value = false;
  }

  async function onRefash() {
    loading.value = true;
    form.startCallDate = form.callDate == null ? null : form.callDate[0];
    form.endCallDate = form.callDate == null ? null : form.callDate[1];
    const curTenantId = getAccount().tenantId;
    getLogListForPub(curTenantId,mergedParams())
      .then(function (data) {
        dataList.value = data.data.list;
        pagination.total = data.data.total;
        pagination.pageSize = data.data.pageSize;
        pagination.currentPage = data.data.currentPage;
        pagination.pageCount = data.data.totalPage;
      })
      .catch(function (err) {
        message(`账户清单加载异常：${err.message}`, {
          type: "error"
        });
      });
    loading.value = false;
  }
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  /** 高亮当前权限选中行 */
  function rowStyle({ row: { id } }) {
    return {
      cursor: "pointer",
      background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }

  onMounted(async () => {
    onSearch();
  });

  watch(isExpandAll, val => {
    val
      ? treeRef.value.setExpandedKeys(treeIds.value)
      : treeRef.value.setExpandedKeys([]);
  });

  watch(isSelectAll, val => {
    val
      ? treeRef.value.setCheckedKeys(treeIds.value)
      : treeRef.value.setCheckedKeys([]);
  });

  return {
    form,
    isShow,
    loading,
    columnsForTable,
    rowStyle,
    dataList,
    pagination,
    onSearch,
    onRefash,
    resetForm,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    detailVisible,
    detailInfo,
    columns,
    openLogDetail
  };
}
